package test.luin.pers.myapplication;

import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class WeatherService {

    public static List<WeatherInfor> getInforFromXML(InputStream is) throws Exception {
        XmlPullParser parser = Xml.newPullParser();
        List<WeatherInfor> weatherInforList = null;
        WeatherInfor weatherInfor = null;

        parser.setInput(is, "utf-8");
        int type = parser.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                case XmlPullParser.START_TAG:
                    if ("infos".equals(parser.getName())) {
                        weatherInforList = new ArrayList<>();
                    } else if ("city".equals(parser.getName())) {
                        weatherInfor = new WeatherInfor();
                        weatherInfor.setId(parser.getAttributeValue(0));
                    } else if ("temp".equals(parser.getName())) {
                        weatherInfor.setTemp(parser.nextText());
                    } else if ("weather".equals(parser.getName())) {
                        weatherInfor.setWeather(parser.nextText());
                    } else if ("name".equals(parser.getName())) {
                        weatherInfor.setName(parser.nextText());
                    } else if ("pm".equals(parser.getName())) {
                        weatherInfor.setPm(parser.nextText());
                    } else if ("wind".equals(parser.getName())) {
                        weatherInfor.setWind(parser.nextText());
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if ("city".equals(parser.getName())) {
                        weatherInforList.add(weatherInfor);
                    }
                    break;
            }
            type = parser.next();
        }
        return weatherInforList;
    }
}
